package com.jf.anmocker.plugin.mockcore.asm

import com.jf.mocker.anotations.IClassMocker
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AnnotationNode

class ClassAnoNode(private val descriptor:String?, val api : Int = Opcodes.ASM9) : AnnotationNode(api, descriptor) {

    private var targetClass : String? = null
    private var isClassMocker = false
    private var listener : ClassAnoVisitListener? = null

    override fun visit(name: String?, value: Any?) {
        super.visit(name, value)
    }

    override fun visitEnd() {
        super.visitEnd()
        if(Type.getDescriptor(IClassMocker::class.java).equals(descriptor)){
            isClassMocker = true
            updateAnoInfo()
            //回调返回结果
            listener?.classVisited(isClassMocker, targetClass)
        }
    }

    private fun updateAnoInfo(){
        for (index in values.indices step 2){
            if(values[index] is String && index+1 < values.size){
                if("value" == values[index] && values[index+1] is String){
                    targetClass = values[index+1] as String
                }
            }else{
                println("${values[index]} value is null")
            }
        }
    }

    public fun getTargetClass() : String?{
        return targetClass
    }

    public fun isClassMocker() : Boolean{
        return isClassMocker
    }

    public fun setVisitListener(listener : ClassAnoVisitListener?){
        this.listener = listener
    }

}

interface ClassAnoVisitListener{
    fun classVisited(isMocker : Boolean, targetClass : String?)
}